<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" label-width="100" :inline="true"
                style="display: flex;flex-direction: column;align-items: center;">
                <div>
                    <el-form-item label="年份">
                        <el-date-picker format="YYYY" value-format="YYYY" v-model="searchInfo.year" type="year"
                            placeholder="请选择" style="width: 220px;"/>
                    </el-form-item>
                    <el-form-item label="申报单位名称">
                        <el-input v-model="searchInfo.unitName" style="width: 220px;"></el-input>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="申报项目名称">
                        <el-input v-model="searchInfo.name" style="width: 220px;"></el-input>
                    </el-form-item>
                    <el-form-item label="是否批复">
                        <el-select v-model.number="searchInfo.approval" placeholder="请选择" style="width: 220px;">
                            <el-option :key="1" label="是" :value="1" />
                            <el-option :key="2" label="否" :value="2" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" :disabled="form.declareIds.length == 0" icon="plus"
                    @click="addUnit">集中批复</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :selectable="selectEnable" />
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="申报年份" prop="year"
                    v-if="checkedColumns.includes('申报年份')"></el-table-column>
                <el-table-column align="left" label="申报单位名称" prop="unitName" width="150" show-overflow-tooltip
                    v-if="checkedColumns.includes('申报单位名称')"></el-table-column>
                <el-table-column align="left" label="维修类型" v-if="checkedColumns.includes('维修类型')" show-overflow-tooltip>
                    <template #default="scope">
                        {{ typeList[scope.row.type - 1]?.name }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="项目名称" prop="name" show-overflow-tooltip
                    v-if="checkedColumns.includes('项目名称')"></el-table-column>

                <el-table-column align="left" label="维修系统" prop="system" show-overflow-tooltip
                    v-if="checkedColumns.includes('维修系统')"></el-table-column>
                <el-table-column align="left" label="申报估算经费（万元）" prop="funding" width="200"
                    v-if="checkedColumns.includes('申报估算经费（万元）')" show-overflow-tooltip>
                </el-table-column>
                <el-table-column align="left" label="是否纳入本年度大中修项目计划" width="220"
                    v-if="checkedColumns.includes('是否纳入本年度大中修项目计划')" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{ adoptList[scope.row.adopt].name }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="审核估算经费（万元）" prop="adoptFunding" width="200"
                    v-if="checkedColumns.includes('审核估算经费（万元）')" show-overflow-tooltip>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="操作" min-width="140"
                    v-if="checkedColumns.includes('操作')">
                    <template #default="scope">
                        <el-button type="primary" link @click="seeDetail(scope.row)">
                            查看详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">集中批复</span>
                    <div>
                        <el-button @click="closeDialog">取消</el-button>
                        <el-button type="primary" @click="enterDialog">确定</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialogFormVisible" ref="yyglForm" label-width="150" :model="form" :rules="rules">
                <el-form-item label="批复内容" prop="approval" style="align-items: normal;">
                    <el-input v-model="form.approval" type="textarea" :rows="6" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="上传附件" prop="approvalFile" style="align-items: normal;">
                    <el-upload ref="uploadRef" v-model:file-list="fileList" :action="adminUrl"
                        :on-success="uploadSuccess" :headers="headerOdj">
                        <el-button type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-drawer>
        <el-drawer v-model="dialog2" :size="1000" :before-close="handleClose2" :show-close="false">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">集中批复</span>
                    <div>
                        <el-button @click="closeDialog2">取消</el-button>
                    </div>
                </div>
            </template>
            <el-form v-if="dialog2" label-width="150" :model="form2">
                <div class="section-title">基本信息</div>
                <el-form-item label="申报年份" prop="approval">
                    <el-input v-model="form2.year" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="申报单位名称" prop="approval">
                    <el-input v-model="form2.unitName" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="项目名称" prop="approval">
                    <el-input v-model="form2.name" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="维修系统" prop="approval">
                    <el-input v-model="form2.system" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="维修内容描述" prop="approval">
                    <el-input v-model="form2.profile" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="申报估算经费" prop="approval">
                    <el-input v-model="form2.funding" style="width: 500px;" disabled />
                    <span style="margin-left: 4px;">万元</span>
                </el-form-item>
                <div class="section-title">审批意见</div>
                <el-form-item label="是否纳入计划" prop="approval">
                    <el-input v-model="adoptList[form2.adopt].name" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="纳入项目计划经费" prop="approval">
                    <el-input v-model="form2.adoptFunding" style="width: 500px;" disabled />
                    <span style="margin-left: 4px;">万元</span>
                </el-form-item>
                <el-form-item label="审核说明" prop="approval">
                    <el-input v-model="form2.examineNotes" style="width: 500px;" disabled />
                </el-form-item>
                <div class="section-title">批复内容</div>
                <el-form-item label="" prop="approval">
                    <el-input v-model="form2.approval" type="textarea" :row="3" style="width: 500px;" disabled />
                </el-form-item>
                <el-form-item label="上传附件" prop="approvalFile" style="align-items: normal;">
                    <el-upload ref="uploadRef" v-model:file-list="fileList" :action="adminUrl"
                        :on-success="uploadSuccess" :headers="headerOdj">
                        <el-button type="primary">文件</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>
<script setup>
import {
    declareMediumPlan,
    mediumPlanApproval,
    declareMediumConstruction
} from '@/api/yewuguanli'
import {
    unitLists
} from '@/api/unit'
import {
    getDyList
} from '@/api/xitongpeizhi'
import { getFileNameFromUrl } from '@/utils/format'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { adoptList } from '@/utils/constant'
const { formItem } = useFormItem()

defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
    declareIds: [],
    approval: '',
    approvalFile: ''
})

const searchInfo = ref({
    year: '',
    unitName: '',
    name: '',
    approval: ''
})

const typeList = ref([
    {
        name: '大中修',
        id: 1
    },
    {
        name: '配置后维修',
        id: 2
    },
    {
        name: '改变房屋布局用途维修',
        id: 3
    }
])

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)

let validateImage = (rule, value, callback) => {
    if (fileList.value.length == 0) {
        callback(new Error('请上传附件'))
    } else {
        callback()
    }
}

const rules = reactive({
    approval: [{ required: true, message: '请输入批复内容', trigger: 'blur' }],
    approvalFile: [{ required: true, validator: validateImage, trigger: 'change' }]
})

function stepChange() {

}

const yyglForm = ref(null)

const initForm = (val) => {
    yyglForm.value.resetFields()
    form.value = {
        declareIds: val == 'success' ? [] : form.value.declareIds,
        approval: '',
        approvalFile: ''
    }
    fileList.value = []
}

const checkedColumns = ref(['序号', '申报年份', '申报单位名称', '维修类型', '项目名称', '维修系统', '申报估算经费（万元）', '是否纳入本年度大中修项目计划', '审核估算经费（万元）', '操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).pffk) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).pffk
}
const columns = ref(['序号', '申报年份', '申报单位名称', '维修类型', '项目名称', '维修系统', '申报估算经费（万元）', '是否纳入本年度大中修项目计划', '审核估算经费（万元）', '操作'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.pffk = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}
const baseInfo = ref({})
const addUnit = (row) => {
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
function selectEnable(row) {
    // 如果当前列的id在id数组中存在，则返回false禁止勾选
    return !row.approval
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await declareMediumPlan({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
getTableData()
const unitData = ref([])
onMounted(() => {
    unitLists().then(res => {
        unitData.value = res.result.data
    })
})

const enterDialog = async () => {
    yyglForm.value.validate(async (valid) => {
        if (valid) {
            const res = await mediumPlanApproval(form.value)
            if (res.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '批复成功'
                })
                page.value = 1
                getTableData()
            }
            initForm('success')
            dialogFormVisible.value = false
        }
    })
}

const onSubmit = () => {
    page.value = 1
    getTableData()
}
const onReset = () => {
    page.value = 1
    searchInfo.value = {
        year: '',
        unitName: '',
        name: '',
        approval: ''
    }
    getTableData()
}
const fileList = ref([])
function uploadSuccess(res) {
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: res.message
        })
        fileList.value.pop()
        return
    }
    form.value.approvalFile = res.result
    yyglForm.value.validateField('approvalFile')
}
let dialogImageUrl = ref()
const dialogVisible = ref(false)
//图片预览
const handlePicturePreview = (file, files) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true
}
const fileList2 = ref([])
function uploadSuccess2() {
    //completionReport
}
const fileList3 = ref([])
function uploadSuccess3() {
    //completionReport
}
const declareIds = ref([])
function handleSelectionChange(val) {
    form.value.declareIds = val.map(item => item.declareId)
}
const form2 = ref({
    approval: '',
    approvalFile: ''
})
const dialog2 = ref(false)
function handleClose2() {
    dialog2.value = false
}

function closeDialog2() {
    dialog2.value = false
}

function seeDetail(row) {
    dialog2.value = true
    form2.value = row
    if (form2.value.approvalFile) {
        fileList.value = [{
            name: getFileNameFromUrl(form2.value.approvalFile),
            url: form2.value.approvalFile
        }]
    }
}
</script>

<style lang="scss">
.flex {
    .area {
        flex: 2;
        background-color: #fff;
        margin: 0.5rem 20px 0.5rem 0;
    }

    .unit {
        flex: 4;
    }
}

.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.btns {
    display: flex;
}

.section-title {
    font-weight: bold;
    font-size: 20px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.tips {
    margin-bottom: 20px;
    color: #ff6666;
    margin-left: 10px;
}
</style>